<template>
    <el-container class="jxc_goods_container">
        <!--物料类目组件-->
        <CategoryTree ref="refCategoryTree" title="物料类目"
                      @event="handleTreeEvent" />
        <el-main>
            <el-card class="box-card">
                <headerTemplate slot="header" ref="header"
                                :table-ref="tableOptions.ref"
                                :toolbar_buttons="headerOption.toolbar_buttons"
                                :toolbar_filter="headerOption.toolbar_filter"
                                :searchForm="searchForm" title="模糊搜索编码、名称、简称、规格、型号、助记码、备注"
                                @event="handleHeaderEvent">
                    <template slot="right_search">
                        <el-select v-model="searchForm.dr" placeholder="请选择"
                                   class="w100" @change="getList(true)"
                                   style="margin-right: 5px;">
                            <el-option label="正常" :value="0" />
                            <el-option label="标记删除" :value="1" />
                        </el-select>
                        <el-form-item label="编号" style="margin-bottom: 0;">
                            <el-input v-model="searchForm.code" style="width: 100px" @change="getList" clearable />
                        </el-form-item>
                        <el-form-item label="名称" style="margin-bottom: 0;">
                            <el-input v-model="searchForm.name" style="width: 100px" @change="getList" clearable />
                        </el-form-item>
                    </template>
                </headerTemplate>
                <vxeTableTemplate ref="xTable" :data="dataList" :options.sync="tableOptions"
                                  @event="handleTableEvent" />
            </el-card>
        </el-main>
    </el-container>
</template>

<script>
import { mapState } from "vuex";
import provide from "@common/mixins/provide";
import poiApi from "@common/api/poiApi";
import GoodsForm from "../dialog/goods/GoodsForm";
import AttributeList from "../dialog/goods/AttributeList";
import GoodsSpecForm from "../dialog/goods/GoodsSpecForm";
import ClothingSpecForm from "../dialog/goods/ClothingSpecForm";

export default {
    extends: provide,
    name: "JxcGoods",
    components: {
        CategoryTree: () => import("../../components/CategoryTree"),
    },
    data() {
        let _this = this;
        return {
            currentNode: [],
            treeNodeKey: {},
            headerOption: {
                toolbar_buttons: [
                    {
                        id: 'refresh',
                        icon: 'el-icon-refresh-right',
                        show: true,
                        method: () => {
                            _this.getList(true);
                        },
                    },
                    {
                        id: 'add',
                        icon: 'fa fa-plus',
                        type: 'primary',
                        show: true,
                        permission: 'jxc:goodsInfo:save',
                        method: () => {
                            _this.openDialog(null, 'add');
                        },
                    },
                    {
                        id: 'edit',
                        icon: 'fa fa-pencil',
                        type: 'success',
                        show: true,
                        permission: 'jxc:goodsInfo:save',
                        method: () => {
                            if (!_this.checkSelection(_this.selectionList)) {
                                return;
                            }
                            _this.openDialog(_this.selectionList[0], 'edit');
                        },
                    },
                    {
                        id: "del",
                        icon: "fa fa-trash-o",
                        type: "danger",
                        show: true,
                        permission: 'jxc:goodsInfo:delete',
                        method: () => {
                            _this.deleteJxcGoods(null, 'batch');
                        },
                    },
                    {
                        id: 'import',
                        label: '导入',
                        icon: 'el-icon-top',
                        type: 'primary',
                        show: true,
                        permission: 'jxc:goodsInfo:import',
                        method: () => {
                            _this.openImportDialog();
                        },
                    },
                    {
                        id: "export",
                        label: '导出',
                        icon: "el-icon-download",
                        type: 'info',
                        class: 'export_btn',
                        show: true,
                        method: () => {
                            _this.exportExcel();
                        },
                    },
                ],
                toolbar_filter: [],
            },
            searchForm: {dr:0},
            dataList: [],
            tableOptions: {
                ref: "goodsTable",
                container: ".jxc_goods_container",
                multiSelect: true,
                columns: [],
                baseColumns: [
                    {
                        label: '类目',
                        prop: 'category_name',
                        align: 'center',
                        minWidth: 90,
                        permission: [ 'common', 'clothing'],
                        sortable:true,
                    },
                    {
                        label: '编号',
                        prop: 'code',
                        align: 'center',
                        minWidth: 90,
                        permission: [ 'common', 'clothing'],
                        sortable:true,
                    },
                    {
                        label: '名称',
                        prop: 'name',
                        align: 'center',
                        minWidth: 90,
                        permission: [ 'common', 'clothing'],
                        sortable:true,
                    },
                    {
                        label: '简称',
                        prop: 'short_name',
                        align: 'center',
                        minWidth: 90,
                        permission: [ 'common', 'clothing'],
                        sortable:true,
                    },
                    {
                        label: '生产状态',
                        prop: 'state',
                        align: 'center',
                        permission: ['clothing'],
                        render: (h, { row }) => {
                            if (row.state === 1) {
                                return h("el-tag", {
                                    style: {
                                        'margin-right': '5px',
                                    },
                                    props: {
                                    },
                                }, '生产');
                            } else if (row.state === 2){
                                return h("el-tag", {
                                    style: {
                                        'margin-right': '5px',
                                    },
                                    props: {
                                        'type': 'danger',
                                    },
                                }, '停产');
                            } else {
                                return h('div', {});
                            }
                        },
                    },
                    {
                        label: '规格',
                        prop: 'spec',
                        align: 'center',
                        minWidth: 90,
                        permission: [ 'common', 'clothing'],
                    },
                    {
                        label: '型号',
                        prop: 'model',
                        align: 'center',
                        minWidth: 90,
                        permission: [ 'common', 'clothing'],
                    },
                    {
                        label: '助记码',
                        prop: 'search_code',
                        align: 'center',
                        minWidth: 90,
                        permission: [ 'common', 'clothing'],
                        sortable:true,
                    },
                    {
                        label: '计量单位',
                        prop: 'base_unit',
                        align: 'center',
                        minWidth: 90,
                        permission: [ 'common', 'clothing'],
                    },
                    {
                        label: '采购价',
                        prop: 'base_buy_price',
                        align: 'center',
                        minWidth: 105,
                        permission: [ 'common', 'clothing'],
                    },
                    {
                        label: '零售价',
                        prop: 'base_sale_price',
                        align: 'center',
                        minWidth: 105,
                        permission: [ 'common', 'clothing'],
                    },
                    {
                        label: '图标',
                        prop: 'icon_file_sid',
                        align: 'center',
                        cellRender: {
                            name: 'TableImage',
                        },
                        permission: [ 'common', 'clothing'],
                    },
                    {
                        label: '删除状态',
                        prop: 'dr',
                        align: 'center',
                        formatter: (row) => {
                            if (_this.$utils.isNotEmpty(row.dr) && row.dr === 1) {
                                return '标记删除';
                            }
                            return '正常';
                        },
                        permission: [ 'common', 'clothing'],
                    },
                ],
                operates: {
                    fixed: 'right',
                    count: 3,
                    list: [
                        {
                            id: "edit",
                            icon: "fa fa-pencil",
                            show: true,
                            type: "success",
                            tooltip: {
                                content: "编辑",
                            },
                            permission: 'jxc:goodsInfo:save',
                            method: (key, row, index) => {
                                _this.openDialog(row, "edit");
                            },
                        },
                        {
                            id: "produce",
                            icon: "el-icon-video-play",
                            show: true,
                            type: "primary",
                            tooltip: {
                                content: "生产",
                            },
                            filter(row) {
                                return _this.setting.industry_config === "clothing" && row.state === 2;
                            },
                            permission: 'jxc:goodsInfo:save',
                            method: (key, row, index) => {
                                _this.handleProduceOrStopGoods(row, 1, '修改物料状态为生产，成功！');
                            },
                        },
                        {
                            id: "stop",
                            icon: "el-icon-video-pause",
                            show: true,
                            type: "danger",
                            tooltip: {
                                content: "停产",
                            },
                            filter(row) {
                                return _this.setting.industry_config === "clothing" && row.state === 1;
                            },
                            permission: 'jxc:goodsInfo:save',
                            method: (key, row, index) => {
                                _this.handleProduceOrStopGoods(row, 2, '修改物料状态为停产，成功！');
                            },
                        },
                        {
                            id: "del",
                            icon: "fa fa-trash-o",
                            type: "danger",
                            tooltip: {
                                content: "删除",
                            },
                            filter(row){
                                return row.dr === 0
                            },
                            show: true,
                            permission: 'jxc:goodsInfo:delete',
                            method: (key, row, index) => {
                                _this.deleteJxcGoods(row, '');
                            },
                        },
                        {
                            id: "resume",
                            icon: "el-icon-refresh-left",
                            type: "primary",
                            filter(row){
                              return row.dr === 1
                            },
                            tooltip: {
                                content: "恢复",
                            },
                            show: true,
                            permission: 'jxc:goodsInfo:delete',
                            method: (key, row, index) => {
                                _this.resumeJxcGoods(row, '');
                            },
                        },
                    ],
                },
                pagination: {
                    pageIndex: 1,
                },
            },
        }
    },
    computed: {
        ...mapState('jxc', [ 'setting' ]),
    },
    mounted() {
        this.init();
    },
    methods: {
        async init() {
            const _this = this;
            await _this.storeDispatch('jxc/initSetting');
            _this.initTableOptions();
            _this.getList(true);
        },
        initTableOptions() {
            const _this = this;
            let columns = _this.tableOptions.baseColumns.map(item => $.extend({}, item));
            columns = columns.filter(item => item.permission.indexOf(_this.setting.industry_config) !== -1);
            let operates = $.extend({}, _this.tableOptions.operates);
            _this.tableOptions = $.extend({}, _this.tableOptions, { columns, operates });
        },
        handleTreeEvent(event) {
            let _this = this;
            if ([ 'all', 'refresh' ].indexOf(event.type) !== -1) {
                _this.treeNodeKey = event.data || {};
                _this.getList(true);
                return;
            }
            _this.currentNode = event.node;
            if (event.type === "nodeClick") {
                _this.treeNodeKey = event.data;
                _this.getList(true);
            }
        },
        // 刷新、查询
        handleHeaderEvent(event) {
            let _this = this;
            _this.searchForm = $.extend({"dr":0}, _this.searchForm, event.searchForm);
            if (event.type === "search") {
                _this.getList(true);
            } else if (event.type === "refresh") {
                _this.getList(true);
            }
        },
        // 获取列表信息
        getList(query) {
            let _this = this;
            if (query) {
                _this.tableOptions = _this.resetTablePagination(_this.tableOptions);
            }
            let queryData = _this.getQueryParams(_this.tableOptions, _this.searchForm);
            // if (_this.treeNodeKey && _this.treeNodeKey.sid) {
            //     queryData.category_sid = _this.treeNodeKey.sid;
            // }
            if (_this.treeNodeKey && _this.treeNodeKey.full_code) {
                queryData.category_full_code = _this.treeNodeKey.full_code;
            }
            _this.fetchData(_this.$api.API_FindJxcGoodss, queryData).then(result => {
                _this.dataList = result.data || [];
                _this.tableOptions = _this.setTableTotal(_this.tableOptions, result);
            }).catch(() => {
            });
        },
        handleTableEvent(event) {
            if (event.type === 'page' || event.type === 'sortChange') {
                this.getList();
                return;
            }
            if (event.type === 'selectionChange') {
                this.selectionList = event.value;
            }
        },
        // 新增、编辑窗体
        openDialog(row, type) {
            const _this = this;
            let title = type === 'add' ? '新增物料' : type === 'edit' ? '编辑物料' : '物料详情';
            let treeData = [];
            if (_this.$refs.refCategoryTree) {
                treeData = _this.$refs.refCategoryTree.treeData;
            }
            if (!row) {
                row = {
                    category_sid: '-1',
                };
                if (_this.treeNodeKey && !_this.$utils.isNotEmptyList(_this.treeNodeKey.children)
                    && _this.$utils.isNotEmpty(_this.treeNodeKey.sid)) {
                    row.category_sid = _this.treeNodeKey.sid;
                }
            }
            _this.$dialog({
                title,
                width: '1200px',
                component: {
                    value: GoodsForm,
                    props: {
                        row,
                        treeData,
                    },
                },
                buttons: type === 'edit' ? [] : [
                    {
                        text: '关闭',
                        click (dialog, $refs) {
                            dialog.visible = false;
                        },
                    },
                    {
                        text: '保存并新增',
                        type: 'primary',
                        click (dialog, $refs) {
                            _this.handleClickConfirmBtn(1, dialog, $refs);
                        },
                    },
                    {
                        text: '保存并复制',
                        type: 'primary',
                        click (dialog, $refs) {
                            _this.handleClickConfirmBtn(2, dialog, $refs);
                        },
                    },
                    {
                        text: '保存',
                        type: 'primary',
                        click (dialog, $refs) {
                            _this.handleClickConfirmBtn(0, dialog, $refs);
                        },
                    },
                ],
                confirmed() {
                    _this.getList();
                    _this.$bus.$emit('updateJxcDashboard');
                },
            });
        },
        handleClickConfirmBtn(operate = 0, dialog, $refs) {
            const _this = this;
            if ($refs.component) {
                $refs.component.confirm(operate).then(valid => {
                    if (valid) {
                        if (operate === 0) {
                            dialog.visible = false;
                        }
                        _this.getList();
                        _this.$bus.$emit('updateJxcDashboard');
                    }
                });
            }
        },
        // 删除
        deleteJxcGoods(row, type) {
            let _this = this;
            let sids = [];
            if (type === 'batch') {
                if (!_this.checkSelection(_this.selectionList, true)) {
                    return;
                }
                sids = _this.selectionList.map(item => item.sid);
            } else {
                sids.push(row.sid);
            }
            _this.confirmDel(sids);
        },
        confirmDel(sids) {
            let _this = this;
            _this.$confirm("是否继续删除？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                _this.fetchData(_this.$api.API_DeleteJxcGoodss, { sids }).then(() => {
                    _this.getList(true);
                    _this.$message.success("删除成功！");
                    _this.$bus.$emit('updateJxcDashboard');
                }).catch(() => {
                });
            }).catch(() => {
            });
        },

        resumeJxcGoods(row, type) {
            let _this = this;
            let sids = [];
            if (type === 'batch') {
                if (!_this.checkSelection(_this.selectionList, true)) {
                    return;
                }
                sids = _this.selectionList.map(item => item.sid);
            } else {
                sids.push(row.sid);
            }
            _this.confirmResume(sids);
        },
        confirmResume(sids) {
            let _this = this;
            _this.$confirm("是否确认恢复？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            }).then(() => {
                _this.fetchData(_this.$api.API_ResumeJxcGoodss, { sids }).then(() => {
                    _this.getList(true);
                    _this.$message.success("恢复成功！");
                    _this.$bus.$emit('updateJxcDashboard');
                }).catch(() => {
                });
            }).catch(() => {
            });
        },
        // 参数Dialog
        openGoodsAttributeDialog(row) {
            let _this = this;
            _this.$dialog({
                title: `${ row.name }-物料参数`,
                width: '820px',
                component: {
                    value: AttributeList,
                    props: {
                        row,
                    },
                },
            });
        },
        // 规格Dialog
        openGoodsSpecsDialog(row) {
            let _this = this;
            _this.$dialog({
                title: `${ row.name }-物料规格`,
                width: '800px',
                component: {
                    value: _this.setting.industry_config === 'clothing' ? ClothingSpecForm : GoodsSpecForm,
                    props: {
                        row,
                    },
                },
                confirmed() {
                    _this.getList();
                },
            });
        },
        // 生产、停产
        handleProduceOrStopGoods(row, state, msg) {
            const _this = this;
            let subData = $.extend({}, row);
            if (!row || !state) {
                return;
            }
            subData.state = state;
            _this.fetchData(_this.$api.API_SaveJxcGoods, subData).then(() => {
                _this.$message.success(msg);
                _this.getList();
            }).catch(() => {
            });
        },
        openImportDialog() {
            const _this = this;
            _this.$ImportExcel({
                title: '导入',
                configFile: _this.$api.IMPORT_CONFIG_FILE_JXC_GOODS,
                downloadFile: '进销存物料信息.xlsx',
                uploadedShowData: true,
                labelWidth: '90px',
                rules: {
                    warehouse_sid: [{ required: true, message: "请选择仓库", trigger: "change" }],
                },
                items: [
                    {
                        prop: 'warehouse_sid',
                        label: '仓库',
                        widget: {
                            name: 'vSelectBottom',
                            props: {
                                type: 'custom',
                                options: {
                                    url: _this.$api.API_FindJxcStockWarehouses,
                                    placeholder: '请选择仓库',
                                    props: {
                                        value: 'sid',
                                        label: 'name',
                                    },
                                    bottomAction: {
                                        permission: 'jxc:wareHouse:save',
                                        permissionUrl: '/jxcBaseWarehouse',
                                    },
                                },
                            },
                        },
                    },
                ],
                event(event) {
                },
                // 点击导入按钮执行方法
                importMethod(list, dialog, formData) {
                    list = _this.resetIndex(list, 'index');
                    _this.handleImportData(list, dialog, formData);
                },
            });
        },
        handleImportData(list, dialog, formData) {
            const _this = this;
            if (!_this.$utils.isNotEmptyList(list)) {
                _this.$message.error('导入数据为空');
                return;
            }
            _this.fetchData(_this.$api.API_ImportJxcGoods, {
                warehouse_sid: formData.warehouse_sid,
                list,
            }).then(res => {
                if (_this.$utils.isNotEmpty(res.message)) {
                    _this.$message.warning(res.message);
                } else {
                    _this.$message.success('导入成功');
                }
                dialog.visible = false;
                if (_this.$refs.refCategoryTree) {
                    _this.$refs.refCategoryTree.initTreeData();
                }
                _this.getList(true);
            }).catch(() => {
            });
        },
        exportExcel() {
            const _this = this;
            let queryData = _this.getQueryParams(_this.tableOptions, _this.searchForm);
            if (_this.treeNodeKey && _this.treeNodeKey.full_code) {
                queryData.category_full_code = _this.treeNodeKey.full_code;
            }
            poiApi.exportExcelTemplateNew({
                template_name: _this.$api.EXPORT_TEMPLATE_NAME_JXC_GOODS_PRODUCT,
                url: _this.$api.API_QueryJxcGoodsProduct4Export,
                params: queryData,
                output_name: '物料信息',
                pageNo: 1,
                pageSize: 100,
                with_date: true,
            });
        },
    }
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.jxc_goods_container {
    /deep/ .el-image-viewer__close {
        top: 40px;
        right: 40px;
        width: 40px;
        height: 40px;
        font-size: 40px;
        color: #FFFFFF;
    }
}
</style>
